package com.heima.Interceptor;
import com.heima.config.JWTConfig;
import com.heima.context.ResidentContext;
import com.heima.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class ResidentInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTConfig jwtConfig;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         log.info("开始进行用户权限校验");
         log .info("{}",jwtConfig.getResidentTokenName());
        String token = request.getHeader(jwtConfig.getResidentTokenName());
        if(StringUtils.isBlank(token)){
            log.info("未携带token");
            response.setStatus(401);
            return false;
        }
        try {
            log.info("jwt校验:{}",token);
            Claims claims = JwtUtil.parseToken(token, jwtConfig.getResidentSecretKey());
            Number numValue = (Number) claims.get("residentId");
            Long id = numValue.longValue();

            ResidentContext.setCurrentId(id);
            log.info("当前用户id为:{}",id);
            return true;
        }
        catch (Exception e){
            log.info("jwt校验失败");
            response.setStatus(401);
            return false;
        }
    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理线程");
        ResidentContext.clear();
    }
}
